package com.myCommon.security.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myCommon.security.entity.LoginUser;
import com.myCommon.security.entity.User;
import com.myCommon.security.mapper.UserMapper;
import com.myCommon.security.service.UserService;
import com.myCommon.util.customerException.CustomerExceptionHandler;
import com.myCommon.util.jwt.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
      
      @Autowired
      private UserMapper userMapper;
      
      @Autowired
      private AuthenticationManager authenticationManager;
      
      @Autowired
      private RedisTemplate redisTemplate;
      
      @Override
      public String login(User user) {
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
            Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
            if (Objects.isNull(authenticate)) {
                  throw new CustomerExceptionHandler("用户名或密码错误");
            }
            LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
            Long userId = loginUser.getUser().getId();
            String token = JwtUtil.createJWT(userId.toString());
            redisTemplate.opsForValue().set("login:"+userId,loginUser);
            return token;
      }
      
      @Override
      public void logout() {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            Long userId = loginUser.getUser().getId();
            redisTemplate.delete("login:" + userId);
            return;
      }
      
      
}
